package com.jiaai.shop.store.api;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;

import com.jiaai.shop.store.entity.*;
import com.jiaai.shop.store.mapper.SMemberMapper;
import com.jiaai.shop.store.service.*;
import com.jiaai.shop.util.IdGenerate;
import com.jiaai.shop.util.MD5;
import com.jiaai.shop.util.redis.RedisUtil;
import com.jiaai.wgj.common.json.RestResultGenerator;

import io.rong.RongCloud;

import io.rong.methods.user.User;
import io.rong.models.response.TokenResult;
import io.rong.models.user.UserModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/app/store")
public class AppController {
    private static final String RONG_CLOUD_TOKEN_CACHE_KEY="rong_token:";
    private static final String RONG_APPKEY="8brlm7uf8tmp3";
    private static final String RONG_APPSECRET="xRiZAiNHGv";
    @Autowired
    private ISOperationHisService isOperationHisService;
    @Autowired
    private ISMemberService isMemberService;
    @Autowired
    private ISExtractMoneyService isExtractMoneyService;
    @Autowired
    private ISSystemconfigService isSystemconfigService;
    @Autowired
    private ISGoodsService isGoodsService;
    @Autowired
    private ISStepsService isStepsService;
    @Autowired
    private SMemberMapper sMemberMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private ISOrderService orderService;

    @Value("${spring.mail.username}")
    private String Sender;
    @RequestMapping("/snedCode")
    public Object sendCodyFormEmail(@RequestParam("email") String email)throws Exception{
        try {

            String yzm=IdGenerate.generateSMSCode(6);
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(Sender);
            message.setTo(email);
            message.setSubject("注册邮箱验证");
            message.setText("您好！"+email+"！\n欢迎注册XXX，请尽快按页面提示完成验证！\n验证码："+yzm+"");
            redisUtil.set(0,"email",yzm,600);
            mailSender.send(message);
            return RestResultGenerator.genSuccessResult("OK");
        }catch (Exception e){
            return RestResultGenerator.genErrorResult("NO");
        }
    }


    @PostMapping("/checkcode")
    public Object checkcode(@RequestParam("code") String code)throws Exception{
        try {
            if(!code.equals(redisUtil.getString(0,"email"))){
                return RestResultGenerator.genErrorResult("验证码错误!");
            }else{
                redisUtil.delKey(0,"email");
            }
            return RestResultGenerator.genSuccessResult("OK");
        }catch (Exception e){
            return RestResultGenerator.genErrorResult("NO");
        }
    }

    /**
     * 注册
     * 传入对象
     * */
    @PostMapping("/insertOrUpdateMember")
    public Object insertOrUpdateMember(@RequestBody SMember sMember)throws Exception{

        try {
                if (sMember.getInvitationPer() != null){
                isMemberService.updateTotalScore(isSystemconfigService.seachRecommendInter(),sMember.getInvitationPer());
            }
            if(sMember.getMemberId()==null) {
                sMember.setMemberId(IdGenerate.generateUserId());
            }
            sMember.setTime(new Date());
            sMember.setMemberPass(MD5.MD5Encode(sMember.getMemberPass()));
            return RestResultGenerator.genSuccessResult(isMemberService.insertOrUpdate(sMember));
        }catch (Exception e){
            return RestResultGenerator.genErrorResult("");
        }
    }
    /**
     * @return
     */
    @GetMapping("/perList")
    public  Object perList(String mId){
        try {

            return  RestResultGenerator.genSuccessResult( isMemberService.selectList(new EntityWrapper().eq("invitationPer",mId)));
        }catch (Exception e){
            return  RestResultGenerator.genErrorResult("error");
        }


    }
    /**
     *
     * @param sMember
     * @return
     */
    @PostMapping("/edit")
    public  Object edit(@RequestBody SMember sMember){
        try {
            isMemberService.updateById(sMember);
            return  RestResultGenerator.genSuccessResult("ok");
        }catch (Exception e){
            return  RestResultGenerator.genErrorResult("error");
        }


    }

    /**
     *
     * @param passowrd
     * @return
     */
    @PostMapping("/edit/password")
    public  Object edit(String mId,String passowrd){
        try {
            SMember member=isMemberService.selectById(mId);
            member.setMemberPass(MD5.MD5Encode(passowrd));
            isMemberService.updateById(member);
            return  RestResultGenerator.genSuccessResult("ok");
        }catch (Exception e){
            return  RestResultGenerator.genErrorResult("error");
        }


    }
  @GetMapping("/custom/token")
  public  Object customToken(){
      String token=redisUtil.getString(0,RONG_CLOUD_TOKEN_CACHE_KEY+"custom");
      if(StringUtils.isEmpty(token) || "null".equals(token) && "nul".equals(token)){
          RongCloud rongCloud = RongCloud.getInstance(RONG_APPKEY, RONG_APPSECRET);
          User rongUser = rongCloud.user;
          UserModel user = new UserModel()
                  .setId("custom")
                  .setName("客服")
                  .setPortrait("http://img2.touxiang.cn/file/20180502/605d6f6e21acf9d8e445082a67eabb28.jpg");
          TokenResult result = null;
          try {
              result = rongUser.register(user);
              token=result.getToken();
              redisUtil.set(0,RONG_CLOUD_TOKEN_CACHE_KEY+"custom",token);
              return  RestResultGenerator.genSuccessResult(token);
          } catch (Exception e) {
              return  RestResultGenerator.genErrorResult("error");
          }
     }
      return  RestResultGenerator.genSuccessResult(token);
  }

    /**
     * 用户登录
     * */
    @PostMapping("/memberLogin")
    public Object memberLogin( String member, String pwd){
        try {
             SMember sm=isMemberService.selectOne(new EntityWrapper().eq("memberName",member));
             if(sm==null){
                 return RestResultGenerator.genErrorResult("用户不存在");
             }else if(!MD5.MD5Encode(pwd).equals(sm.getMemberPass())){
                 return RestResultGenerator.genErrorResult("密码错误");
             }
             Map<String,Object> smMap=new HashMap<>();
            smMap.put("token","");
            smMap.put("member",sm);
            String token=redisUtil.getString(0,RONG_CLOUD_TOKEN_CACHE_KEY+member);
            if(StringUtils.isEmpty(token) || "null".equals(token) && "nul".equals(token)){
                RongCloud rongCloud = RongCloud.getInstance(RONG_APPKEY, RONG_APPSECRET);
                User rongUser = rongCloud.user;
                UserModel user = new UserModel()
                        .setId(member)
                        .setName(sm.getNickName())
                        .setPortrait("http://img2.touxiang.cn/file/20180502/605d6f6e21acf9d8e445082a67eabb28.jpg");
                TokenResult result = rongUser.register(user);
                token=result.getToken();
                redisUtil.set(0,RONG_CLOUD_TOKEN_CACHE_KEY+member,token);
            }
            smMap.put("rongToken",token);
            return RestResultGenerator.genSuccessResult(smMap);
        }catch (Exception e){
            return RestResultGenerator.genErrorResult("error");
        }
    }


    /**
     * 购买商品
     * 需要传入对象
     */
    @PostMapping("/insertOperationHis/{mId}")
    public Object insertOperationHis(@RequestBody SGoods sGoods, @PathVariable("mId") String mId)throws Exception{
        SOperationHis sOperationHis=new SOperationHis();
        Map map=new HashMap();
        try {
            sOperationHis.setTime(new Date());
            sOperationHis.setMember(mId);
            sOperationHis.setOperationHis("购买商品");
            sOperationHis.setGoodsId(sGoods.getId());
            map.put("addIntegral",isMemberService.updateeturnIntegral(sGoods.getIntegral(),sGoods.getLv(),mId));
            map.put("addOperationHis",isOperationHisService.insert(sOperationHis));
            return RestResultGenerator.genSuccessResult(map);
        }catch (Exception e){
            return RestResultGenerator.genErrorResult("");
        }
    }

    /**
     * 查询提现
     * */
    @GetMapping("/seachExtract")
   public Object seachExtract(Integer curr,String memberId)throws Exception{
        try {
            Page page=new Page(curr,20);
            SearchExtractVo extractVo=new SearchExtractVo();
            extractVo.setMemberId(memberId);
            return RestResultGenerator.genSuccessResult(isExtractMoneyService.List(page,extractVo));
        }catch (Exception e){
            return RestResultGenerator.genErrorResult("");
        }
    }

    /**
     * 提现申请
     **/
    @PostMapping("/extractMoney")
    public Object extractMoney(@RequestBody SExtractMoney sExtractMoney){
        try {
            sExtractMoney.setTime(new Date());
            sExtractMoney.setExtractProportion(isSystemconfigService.seachProportion());
            double actualamount =(double)isSystemconfigService.seachProportion()/100;
            BigDecimal je=new BigDecimal(Float.parseFloat(sExtractMoney.getExtractNumber())*actualamount).setScale(2,BigDecimal.ROUND_HALF_UP);
            sExtractMoney.setAmount(je);
            isMemberService.updateMenberbyId(sExtractMoney);
            return RestResultGenerator.genSuccessResult(isExtractMoneyService.insertOrUpdate(sExtractMoney));
        }catch (Exception e){
            return RestResultGenerator.genErrorResult(e.getMessage());
        }
    }

//    /**
//     * 查找商品
//     * */
//    @GetMapping("/seachGoods")
//    Object seachGoods(@RequestParam int curr)throws Exception{
//        try {
//            Page page=new Page(curr,8);
//            return RestResultGenerator.genSuccessResult(isGoodsService.seachGoods(page));
//        }catch (Exception e){
//            return RestResultGenerator.genErrorResult("");
//        }
//    }
    /**
     * 查找商品
     * */
    @GetMapping("/seachGoods")
    Object seachGoods(@RequestParam Integer curr,SGoods sGoods)throws Exception{
        try {
            EntityWrapper wrapper =new EntityWrapper();
            wrapper.like("goodsName",sGoods.getGoodsName());
            if(sGoods.getState()!=null) {
                wrapper.eq("state", sGoods.getState());
            }
            Page page=new Page(curr,100);
            return RestResultGenerator.genSuccessResult(isGoodsService.findGoodsAll(page,wrapper));
        }catch (Exception e){
            return RestResultGenerator.genErrorResult("");
        }
    }

    /**
     *单个
     *商品详情
     */
    @GetMapping("/seachIdGoods")
    Object seachIdGoods(@RequestParam int id)throws Exception{
        try {
            return RestResultGenerator.genSuccessResult(isGoodsService.selectById(id));
        }catch (Exception e){
            return RestResultGenerator.genErrorResult("");
        }
    }

    /**
     *
     */





    /**
     * 查询流程步骤
     * */
    @GetMapping("/seachStep")
     public Object seachStep()throws Exception{
        try {
            return RestResultGenerator.genSuccessResult(isStepsService.seachStep());
        }catch (Exception e){
            return RestResultGenerator.genErrorResult("");
        }
    }

    /**
     * 提现处理，更改提现状态
     *
     * */
    @PostMapping("/updatePresentScore")
    public Object updatePresentScore(@RequestParam String mId,Integer presentScore)throws Exception{
        try {
            return RestResultGenerator.genSuccessResult(sMemberMapper.updatePresentScore(mId,presentScore));
        }catch (Exception e){
            return RestResultGenerator.genErrorResult("");
        }
    }

    /**
     * 会员表忘记密码
     *
     * */
    @PostMapping("/updateMemberPass")
    public Object updateMemberPass(@RequestParam String memberName,String memberPass)throws Exception{
        try {
            return RestResultGenerator.genSuccessResult(sMemberMapper.updateMemberPass(memberName,MD5.MD5Encode(memberPass)));
        }catch (Exception e){
            return RestResultGenerator.genErrorResult("");
        }
    }


}
